<?php
namespace Admin\Controller;
use Admin\Model\Page;
use Think\Exception;

class RoleController extends BaseController
{
    public function __construct($baseModel)
    {
        parent::__construct(D('Role'));
        $this->bcItemPush('角色列表', U('Role/index'));
    }
	private static $_validate = array(
		array('role_name', 'require', '角色名称不能为空！', 1, 'regex', 3),
		array('role_name', '1,30', '角色名称的值最长不能超过 30 个字符！', 1, 'length', 3),
	);
	public function index()
	{
		$model = D('Role');
		//构建查询条件
		$pagesize = 10;
        $role_name = I('role_name');
		$pagenumber = I('pagenum', '');
		if (empty($pagenumber) || $pagenumber <= 0)
			$pagenumber = 1;
		if ($role_name != '') {
			$map['role_name'] = array('like', '%' . $role_name . '%');
		}
		//查询
		$list = $model->getByConditionPage($map,$pagenumber,$pagesize);
		$recordcount = $model->where($map)->count();
		//封装分页对象
		$page = new Page($pagenumber, $recordcount, $pagesize);
		$page = (array)$page;//转换为数组

		//将权限名称添加到数组
		

		//显示数据
		$this->assign('page', $page);
		$this->assign('role_name', $role_name);
		$this->assign('pagenumber', $pagenumber);
		$this->assign('roleList', $list);
		$this->assign('recordcount', $recordcount);
		$this->display();
	}

	public function privileges($role_id=0){
		$model = D('Privilege');
//		$privilegeList = $model->getTopPrivilegeList();
		//获取所有权限列表
		$privilegeList = $model->field('id,name,parent_id as pid')->select();
		$rolePrivilegeList =null;
		if($role_id!=0){
			//获取当前角色的权限列表
			$Role = D('Role');
			$rolePrivilegeList =$Role->getPrivilegeListByRole($role_id);
		}
		for($i =0;$i<count($privilegeList);$i++){
			$privilege = $privilegeList[$i];
			for($j =0;$rolePrivilegeList!=null && $j<count($rolePrivilegeList);$j++){
				if($rolePrivilegeList[$j]['id'] == $privilege['id']){
					$privilegeList[$i]['checked']=true;
					continue;
				}
			}
			if($privilege['pid'] != 0){
				//如果不为根节点
			}else{
				$privilegeList[$i]['open']=true;
			}
		}
		$privilegeList = (array)$privilegeList;
		$this->ajaxReturn($privilegeList);
	}


	public function addUI()
	{
		$model = D('Privilege');
//		$privilegeList = $model->getTopPrivilegeList();
		$privilegeList = $model->field('id,name,parent_id pId')->select();
        $this->bcItemPush('添加角色', U('Role/addUI'));
		$this->assign('topPrivilegeList', $privilegeList);
//		var_dump($privilegeList);
		$this->display('save');
	}
	protected function doAddBefore($data)
	{
		$this->checkSave($data,'添加');
	}

	public function add()
	{
		parent::add(self::$_validate);
	}


	protected function doAddAfter($data, $success)
	{
		$this->doCascadeSave($data,$success,'添加');
	}

	public function editUI($id)
	{
		$Role = D('Role');
		$where['id'] = ':id';
		$Role->where($where)->bind($where['id'],$id)->find();
        $this->bcItemPush('编辑角色', U('Role/editUI/'.$id));
		$this->assign('role', $Role->data());
		$this->display('save');
	}
	protected function doEditBefore($data)
	{
		$this->checkSave($data,'修改');
		$role_privilege = D('role_privilege');
		try {
			//删除t_role_privilege表的相关数据
			$where['role_id'] = ':role_id';
			$role_privilege->where($where)->bind($where['role_id'], $data['id'])->delete();
//			//删除t_admin_role表的相关数据
//			D('admin_role')->where($where)->bind($where['role_id'], $id)->delete();
		}catch (Exception $e){
			$role_privilege->rollback();//回滚事务
			parent::retJson(false, '修改失败，无法删除关联数据');
		}
	}

	public function edit()
	{
		parent::edit(self::$_validate);
	}
	protected function doEditAfter($data, $success)
	{
		$this->doCascadeSave($data,$success, '修改');
	}

	public function doDeleteBefore( $id)
	{
		try {
			//删除t_role_privilege表的相关数据
			$where['role_id'] = ':role_id';
			D('role_privilege')->where($where)->bind($where['role_id'], $id)->delete();
			//删除t_admin_role表的相关数据
			D('admin_role')->where($where)->bind($where['role_id'], $id)->delete();
		}catch (Exception $e){
			$this->baseModel->rollback();//回滚事务
			parent::retJson(false, '删除失败，无法删除关联数据');
		}
	}

	public function delete($id)
	{
		parent::delete($id);
	}
	/**
	 * @param $data
	 * @param $option 当前操作
	 */
	private function checkSave($data, $option)
	{
		$Privilege = D('Role');
		$where['role_name'] = ':role_name';
		$count = $Privilege->where($where)->bind($where['role_name'], $data['role_name'])->count();
		if(($option =='修改' && $count>=2) || ($option =='添加' && $count>=1) ){
			parent::retJson(false, $option.'失败，角色名称不能重复');
		}
	}

	/**
	 * 插入数据到关联的表中
	 * @param $data
	 * @param $success
	 * @param $option 操作名称 添加或修改
	 */
	private function doCascadeSave($data,$success, $option)
	{
		if (!$success && $success != 0)
			return;
		$pri_ids = I('post.pri_ids');
		try {
			$Role_Privilege = D('role_privilege');
			foreach ($pri_ids as $key => $value) {
				$role_privilege =null;
				if($option == '添加') {
					$role_privilege['role_id'] = $success;
				}elseif ($option == '修改'){
					$role_privilege['role_id'] = $data['id'];
				}
				$role_privilege['pri_id'] = $value;
				$Role_Privilege->add($role_privilege);
			}
		} catch (Exception $e) {
			$this->baseModel->rollback();//回滚事务
			parent::retJson(false, $option.'失败,无法添加指定权限');
		}
	}
}